package com.yanxu.threadandobjectmethods.print;

import java.util.Stack;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025/3/20-2025
 * @Description: 交替打印，使用 synchronized
 */
public class TurnsPrintBySynchronized {
    static Object object = new Object();
    static int a = 0;

    public static void main(String[] args) {
        //偶数线程
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                while (a < 100) {
                    synchronized (object) {
                        if (a % 2 == 0) {
                            System.out.println(Thread.currentThread().getName() + "---" + a);
                            a++;
                        }
                    }
                }

            }
        }, "偶数线程");

        //奇数线程
        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                while (a < 100) {
                    synchronized (object) {
                        if (a % 2 != 0) {
                            System.out.println(Thread.currentThread().getName() + "---" + a);
                            a++;
                        }
                    }
                }
            }
        }, "奇数线程");

        //启动线程
        thread1.start();
        thread2.start();

    }
}